package com.dayaokeji.rhythmschoolstudent.utils;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import com.bilibili.boxing.utils.BoxingLog;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.server_api.domain.FileInfo;
import com.dayaokeji.server_api.domain.ForgetPassword;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.Okio;

/**
 * Created by Zeno on 2017/10/3.
 */

public class FileUtil {

    private static final String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
    private static final String APP_PATH = ROOT_PATH+File.separator+"rhythmschool"+File.separator;
    public static final String RESOURCE_DIR = APP_PATH+"resource_dir"+File.separator;

    /**
     * 保存文件
     * @param responseBody
     * @param fileInfo
     */
    public static void saveFile(ResponseBody responseBody, FileInfo fileInfo) {
        BufferedSink sink = null;
        try{
            String dirPath = RESOURCE_DIR;
            File dir = new File(dirPath);
            if (!dir.isDirectory()){
                dir.mkdirs();
            }
            sink = Okio.buffer(Okio.sink(new File(dirPath+fileInfo.getName())));
            sink.writeAll(responseBody.source());
            sink.flush();

            ToastUtils.success(App.getAppContext().getString(R.string.file_download_success));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (sink != null) {
                try {
                    sink.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     * @param fileName
     */
    public static boolean deleteFile(String fileName) {
        try{
            if (isFileExists(fileName)) {
                File file = new File(RESOURCE_DIR, fileName);
                file.delete();
            }
            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 文件是否存在
     * @param fileName
     * @return
     */
    public static boolean isFileExists(String fileName) {
        File file = new File( RESOURCE_DIR, fileName);
        return file.exists();
    }

    /**
     * 打开文件
     */
    public static void openFile(Context context,FileInfo fileInfo) {
        MimeTypeMap myMime = MimeTypeMap.getSingleton();
        Intent newIntent = new Intent(Intent.ACTION_VIEW);
        String mimeType = myMime.getMimeTypeFromExtension(fileInfo.getExtension());
        final Uri uriForFile = FileProvider.getUriForFile(context, "com.dayaokeji.rhythmschoolstudent.provider", new File(RESOURCE_DIR, fileInfo.getName()));
        newIntent.setDataAndType(uriForFile,mimeType);
        newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Intent chooser = Intent.createChooser(newIntent, App.getAppContext().getString(R.string.please_choose_open_file_app));
        ComponentName componentName = chooser.resolveActivity(context.getPackageManager());
        if (componentName != null) {
            try {
                context.startActivity(chooser);
            } catch (ActivityNotFoundException e) {
                ToastUtils.warning(App.getAppContext().getString(R.string.not_found_open_file));
            }
        }else{
            ToastUtils.warning(App.getAppContext().getString(R.string.not_found_open_file_app));
        }

    }

    /**
     * 打开文件
     */
    public static void openFile(Context context,File file) {
        MimeTypeMap myMime = MimeTypeMap.getSingleton();
        Intent newIntent = new Intent(Intent.ACTION_VIEW);
        String mimeType = myMime.getMimeTypeFromExtension(com.litesuits.common.utils.FileUtil.getExtensionName(file.getName()));
        final Uri uriForFile = FileProvider.getUriForFile(context, "com.dayaokeji.rhythmschoolstudent.provider", new File(RESOURCE_DIR, file.getName()));
        newIntent.setDataAndType(uriForFile,mimeType);
        newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Intent chooser = Intent.createChooser(newIntent, App.getAppContext().getString(R.string.please_choose_open_file_app));
        ComponentName componentName = chooser.resolveActivity(context.getPackageManager());
        if (componentName != null) {
            try {
                context.startActivity(chooser);
            } catch (ActivityNotFoundException e) {
                ToastUtils.warning(App.getAppContext().getString(R.string.not_found_open_file));
            }
        }else{
            ToastUtils.warning(App.getAppContext().getString(R.string.not_found_open_file_app));
        }

    }

    public static int getFileType(String fileExt) {
        String ext = fileExt.toUpperCase();
        if ("PNG".equals(ext) || "JPG".equals(ext) || "JPEG".equals(ext)) {
            return 1;
        }else if ("PDF".equals(ext)) {
            return 2;
        }else if ("EXCEL".equals(ext)){
            return 3;
        }else if ("WORD".equals(ext)) {
            return 4;
        }
        else{
            return 9;
        }
    }

    /**
     * 根据文件扩展名得到文件类型
     * @param fileExt
     * @return fileType {@link FileType}
     */
    public static FileType getShowFileType(String fileExt) {
        String ext = fileExt.toUpperCase();
        if ("PNG".equals(ext) || "JPG".equals(ext) || "JPEG".equals(ext)) {
            return FileType.IMAGE;
        }else if ("PDF".equals(ext)) {
            return FileType.PDF;
        }else if ("EXCEL".equals(ext)){
            return FileType.EXCEL;
        }else if ("WORD".equals(ext)) {
            return FileType.WORD;
        }else if ("PPT".equals(ext)){
            return FileType.PPT;
        }else if ("PSD".equals(ext)){
            return FileType.PSD;
        }else if ("AI".equals(ext)){
            return FileType.AI;
        }else if ("FLA".equals(ext)){
            return FileType.FLA;
        }else if ("HTML".equals(ext)){
            return FileType.HTML;
        }else if ("MP3".equals(ext) || "WMA".equals(ext) || "AAC".equals(ext)){
            return FileType.AUDIO;
        }else if ("TXT".equals(ext)){
            return FileType.TXT;
        }else if ("MP4".equals(ext) || "MPEG".equals(ext) || "FLV".equals(ext) || "WMV".equals(ext) || "AVI".equals(ext)){
            return FileType.VIDEO;
        }else if ("ZIP".equals(ext) || "RAR".equals(ext) || "GZ".equals(ext) || "7Z".equals(ext) || "TAR".equals(ext)){
            return FileType.ZIP;
        }
        else{
            return FileType.OTHER;
        }
    }


    @Nullable
    public static String getCacheDir(@NonNull Context context) {
        if(context == null) {
            return null;
        } else {
            context = context.getApplicationContext();
            File cacheDir = context.getCacheDir();
            if(cacheDir == null) {
                BoxingLog.d("cache dir do not exist.");
                return null;
            } else {
                String result = cacheDir.getAbsolutePath() + "/crop";

                try {
                    createFile(result);
                } catch (InterruptedException | ExecutionException var4) {
                    BoxingLog.d("cache dir " + result + " not exist");
                    return null;
                }

                BoxingLog.d("cache dir is: " + result);
                return result;
            }
        }
    }

    public static boolean createFile(String path) throws ExecutionException, InterruptedException {
        if(TextUtils.isEmpty(path)) {
            return false;
        } else {
            File file = new File(path);
            return file.exists() || file.mkdirs();
        }
    }

    public enum FileType{
        /**
         * 图片
         */
        IMAGE,
        PPT,
        EXCEL,
        WORD,
        TXT,
        PDF,
        AI,
        FLA,
        PSD,
        /**
         * 网页
         */
        HTML,
        /**
         * 音频
         */
        AUDIO,
        /**
         * 视频
         */
        VIDEO,
        XD,
        /**
         * 压缩
         */
        ZIP,
        OTHER
    }
}
